<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Nav extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $navs = get_cates('nav', 0);
        $this->assign('navs', $navs);
        return view();
    }

    // 添加/编辑前台导航
    public function save_nav() {
        $id = input('param.id', 0);
        // 获取分类树
        $navs = get_cates('nav', 0);
        $this->assign('navs', $navs);
        if (Request::instance()->isPost()) {
            // 提交数据
            $data = [
                'pid' => input('param.pid'),
                'name' => input('param.name'),
                'url' => input('param.url')
            ];

            if (input('param.pid') > 0) {
                $cate = db('nav')->where('id', input('param.pid'))->find();
                $data['level'] = $cate['level'] + 1;
            }

            $post_image = input('param.image', '');
            if ($post_image) {
                // 如果图片有值  则获取旧图并删除
                $image = db('nav')->where('id', $id)->value('image');
                if ($image) {
                    unlink('./uploads/nav/'.$image);
                }
                $data['image'] = $post_image;
            }

            if ($id > 0)  {
                $text = '编辑';
                $rs = db('nav')->where('id', $id)->update($data);
            } else {
                $text = '添加';
                $rs = db('nav')->insert($data);
            }
            if ($rs !== false)
                return json(['code' => 200, 'msg' => $text . '导航成功！']);
            else
                return json(['code' => 0, 'msg' => $text . '导航失败！']);
        } else {
            $text = $id > 0 ? '编辑' : '添加';
            $nav = [];
            if ($id > 0) {
                $nav = db('nav')->where('id', $id)->find();
            }
            $navs_url = db('nav')->field('name, url')->where('pid', 0)->select();
            $this->assign('navs_url', $navs_url);
            $this->assign('nav', $nav);
            $this->assign('text', $text);
            return view();
        }
    }

    // 删除分类
    public function del_nav() {
        $id = input('param.id', 0);

        $category = db('nav')->where('pid', $id)->count();
        if ($category > 0) {
            return json(['code' => 0, 'msg' => '导航下面有子导航，不能删除！']);
        }
        $rs = db('nav')->where('id', $id)->delete();
        if ($rs !== false) {
            return json(['code' => 200, 'msg' => '删除成功！']);
        } else {
            return json(['code' => 0, 'msg' => '删除失败！']);
        }
    }
}
